package com.lee.rabbitmq.util;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.*;
import java.util.*;
import java.util.concurrent.TimeoutException;

/**
 * Rabbit工具类，用于获取连接与通道、关闭连接与通道
 *
 * @author Lee
 * @createDate 2021/12/14 11:25
 */
public class RabbitMqUtil {

    /**
     * 获取连接（Connection）
     *
     * @return Connection 获取连接
     * @throws IOException
     * @throws TimeoutException
     * @author Lee
     * @createDate 2021/12/14 11:48
     */
    public static Connection getConnection() {

        Properties prop = new Properties();
        RabbitMqUtil util = new RabbitMqUtil();
        //加载配置文件
        InputStream in = util.getClass().getClassLoader().getResourceAsStream("rabbitmq.properties");
        String host = null;
        int port = 0;
        String username = null;
        String password = null;
        try {
            prop.load(in);
            host = prop.getProperty("host");
            port = Integer.valueOf(prop.getProperty("port"));
            username = prop.getProperty("username");
            password = prop.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }

        //创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        /**
         * 配置RabbitMQ的连接信息
         */
        //指定ip
        factory.setHost(host);
        //指定端口
        factory.setPort(port);
        //指定账号
        factory.setUsername(username);
        //指定密码
        factory.setPassword(password);
        //定义连接
        Connection connection = null;

        try {
            //获取连接
            connection = factory.newConnection();
        } catch (
                IOException e) {
            e.printStackTrace();
        } catch (
                TimeoutException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 关闭传入的连接与通道（Connection、Channel）
     *
     * @param connection 关闭这个连接
     * @param channel    关闭这个通道
     * @throws IOException
     * @throws TimeoutException
     * @author Lee
     * @createDate 2021/12/14 11:51
     */
    public static void close(Connection connection, Channel channel) {
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
